let sql = require('../sql/sql');
let data = require('../libs/data');
var db = require('../libs/db');
var utils = require('../libs/utils');
var shortId = require('shortid');
var Topic = db.Topic;
var Code = db.code;
var Activity = db.Activity;
var Promsise = require('bluebird');
var jwt = require("jsonwebtoken");
var client = require('redis').createClient();
function randomWord(randomFlag, min, max) {
    var str = "",
        range = min,
        // arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];

    // 随机产生
    if (randomFlag) {
        range = Math.round(Math.random() * (max - min)) + min;
    }
    for (var i = 0; i < range; i++) {
        pos = Math.round(Math.random() * (arr.length - 1));
        str += arr[pos];
    }
    return str;
}
async function getCode() {
    var code = randomWord(false, 4);
    var rows = await Activity.findOne({
        where: {
            code: code
        }
    });
    console.log("是否为空：",rows==null);
    if(rows==null){
        return code;
    }else{
        return getCode();
    }
}
//验证短信码
function verifysms(code) {
    return true;
}

module.exports = {
    // faa(){
    //     var code = [];
    //     for(i=0;i<3100;i++){
    //         var codeData = {
    //             code: randomWord(false, 6),
    //         };
    //         Code.create(codeData);
    //     }
    // },
    // 创建活动
    async add (req, res) {
        var name = req.body.name;
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        var codeid = shortId.generate();
        var acid = req.body.acid;
        var step = req.body.step;
        var code = await getCode();
        var tag = '1';
        var activityData = {
            code: code,
            codeid: codeid,
            userid: userData.userid,
            name: name == undefined ? '民间品酒师发现之旅' + codeid : name,
            acid: acid,
            step:step,
            tag:tag,
        };
        var answer1 = '';
        var answer2 = '';
        var answer3 = '';
        var answer4 = '';
        answer1 = '浓香8：芝香2';
        answer2 = '浓香5：芝香5';
        answer3 = '浓香2：芝香8';
        answer4 = '浓香1：芝香10';
        var topicDatas = [{
            codeid: codeid,
            okanswer: req.body.answers[0],
            answer1: answer1,
            answer2: answer2,
            answer3: answer3,
            answer4: answer4
        }, {
            codeid: codeid,
            okanswer: req.body.answers[1],
            answer1: answer1,
            answer2: answer2,
            answer3: answer3,
            answer4: answer4
        }, {
            codeid: codeid,
            okanswer: req.body.answers[2],
            answer1: answer1,
            answer2: answer2,
            answer3: answer3,
            answer4: answer4
        }, {
            codeid: codeid,
            okanswer: req.body.answers[3],
            answer1: answer1,
            answer2: answer2,
            answer3: answer3,
            answer4: answer4
        }];
        return db.sequelize.transaction(function (t) {
            return Activity.create(activityData, {transaction: t}).then(function (order) {
                return Promsise.map(topicDatas, function (topicData) {
                    return Topic.create(topicData, {transaction: t});
                });
            });
        }).then(function (result) {
            console.log('activityData',activityData);
            data.code = '200';
            data.msg = '添加数据成功';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '添加数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });
    },
    // 查询活动
    find (req, res) {
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        return Activity.findOne({
            where: {
                userid: userData.userid,
                active: '1'
            },
            limit: 1,
            order: 'id DESC'
        }).then(function (user) {
            console.log(user.code);

            client.get('activityid_start_time_' + user.codeid, function (err, object) {
                if (!err) {
                    return user.getCodeid().then(function (result) {
                        data.code = '200';
                        data.msg = '查询数据成功';
                        data.data = result;
                        data.activityCode = user.code;
                        data.activityid = user.codeid;
                        data.isActivity = object != null ? true : false;
                        res.status(200).send(JSON.stringify(data));
                    });
                }
            });
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });
    },
    //删除活动
    delete(req, res){
        var activityid = req.body.activityid;
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        return Activity.destroy({
            where: {
                userid: userData.userid,
                codeid: activityid,
                active:'1'
            },
        }).then(function (result) {
            data.code = '200';
            data.msg = '删除数据成功';
            data.data = result;
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '删除数据失败';
            data.data = '';
            res.status(200).send(JSON.stringify(data));
        });

    },
    updateActive(codeid){
        return Activity.update({
            active: '2'
        }, {
            where: {
                codeid: codeid
            }
        }).then(function (user) {
            return true;
        }).catch(function (err) {
            console.log(err);
            return false;
        });
    },
    //查看活动列表
    findList(req, res){
        var token = utils.getToken(req.headers);
        var userData = jwt.verify(token, 'secret');
        var sql = 'select a.codeid,DATE_FORMAT(a.createtime,"%m-%d") time,a.name from jyj_activity a where a.userid = :userid order by a.id desc';
        db.sequelize.query(sql, {
            replacements: {userid: userData.userid},
            type: db.sequelize.QueryTypes.SELECT
        }).then(function (result) {
            console.log(result.length);
            data.code = '200';
            data.msg = '查询数据成功';
            data.data = result;
            res.status(200).send(JSON.stringify(data));
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            res.status(200).send(JSON.stringify(data));
        });
    },
    //查看本次活动结果
    findThisResult(req, res){
        var codeid = req.body.codeid;
        var mm = {
            title: '',
            total: 0,
            promotion: [],
            noprom: 0
        }
        var sql = 'SELECT IFNULL(a.totalNum, 0) totalNum, concat( DATE_FORMAT(b.createtime, "%m月%d日"), " ", b. NAME ) name FROM ( SELECT count(1) totalNum, codeid FROM jyj_usertopic a WHERE a.codeid = :codeid ) a RIGHT JOIN jyj_activity b ON a.codeid = b.codeid WHERE b.codeid = :codeid';
        db.sequelize.query(sql, {
            replacements: {codeid: codeid},
            type: db.sequelize.QueryTypes.SELECT
        }).then(function (result) {
            console.log(result);
            mm.title = result[0].name;
            mm.total = result[0].totalNum;
            var sql1 = 'SELECT a.*, b.phone name, b.username FROM ( SELECT b.createtime, b.userid, b.totaltime FROM ( SELECT GROUP_CONCAT(okanswer) okanswer, a.createtime FROM jyj_topic a WHERE a.codeid = :codeid ) a, ( SELECT a.userid, a.codeid, a.totaltime, a.createtime, CONCAT( a.topic1, ",", a.topic2, ",", a.topic3 ) okanswer FROM jyj_usertopic a WHERE a.codeid = :codeid ) b WHERE a.okanswer = b.okanswer ) a LEFT JOIN jyj_user b ON a.userid = b.userid ORDER BY a.createtime DESC';
            db.sequelize.query(sql1, {
                replacements: {codeid: codeid},
                type: db.sequelize.QueryTypes.SELECT
            }).then(function (result) {
                mm.promotion = result;
                mm.noprom = mm.total - result.length;
                console.log(mm);
                data.code = '200';
                data.msg = '查询数据成功';
                data.data = mm;
                res.status(200).send(JSON.stringify(data));
            });
        }).catch(function (err) {
            data.code = '101';
            data.msg = '查询数据失败';
            res.status(200).send(JSON.stringify(data));
        });
    }
};